import type { AxiosError, AxiosResponse } from 'axios'
import axios from 'axios'
import { useStorage } from '@vueuse/core'
import { Message } from '@arco-design/web-vue'

const accessToken = useStorage('token', '')
export const Method = {
  GET: 'get',
  POST: 'post',
  PUT: 'put',
  DELETE: 'delete',
}

export const GATEWAYUrl: string = (process.env.NODE_ENV === 'development'
  ? ENV.BASE.API_DEV.GATEWAY
  : ENV.BASE.API_PROD.GATEWAY)

const service = axios.create({
  timeout: 20000, // 请求超时时间
  baseURL: GATEWAYUrl,
})

// request拦截器
service.interceptors.request.use(
  (config: any) => {
    // 删除空参数
    if (config.params) {
      for (const [key, value] of Object.entries(config.params)) {
        if (value === undefined || value === null || value === '')
          delete config.params[key]
      }
    }
    if (config.data) {
      for (const [key, value] of Object.entries(config.data)) {
        if (value === undefined || value === null || value === '')
          delete config.data[key]
      }
    }

    const requestHeader = {
      accessToken: accessToken.value,
    }

    config.headers = { ...config.headers, ...requestHeader }
    return config
  },
  (error: AxiosError) => {
    return error
  },
)

/**
 * response 拦截器
 * 状态码正常 返回接口数据
 * 状态码异常 返回接口数据 + 头部信息
 */
service.interceptors.response.use(
  async (response: AxiosResponse) => {
    return response
  },
  async (error) => {
    const { response } = error
    const token: any = localStorage.getItem('token')
    if (response.status === 403)

      return

    if (token && response.status === 401) {
      // token过期
    } // 如果当前返回没登录
    else if (response.data.code === 20004 || response.data.code === 20003) {
      Message.error(response.data.message)
    }
    else if (
      (response.status === 200 && !response.data.success)
      || response.status === 400
    ) {
      Message.error(response.data.message)
    }
    return error
  },
)

/**
 * 抛出request
 * @param options
 * @returns
 */
export default function request(options: object): Promise<AxiosResponse> {
  return service(options)
}
